from windows import Ui_Dialog
from getSettings import getSettings
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
from get_gendatbase import get_en
import json
from PyQt5.QtWidgets import QApplication
import sys
import pytesseract
from PIL import Image
from PIL import ImageOps
import sqlite3


def try_translate():
    # 读取配置文件
    settings_file = open('settings.json', 'r')
    settings = json.loads(settings_file.readline())
    positions = settings['position']
    screen = QApplication.primaryScreen()

    # 对应的坐标截屏
    pix = screen.grabWindow(QApplication.desktop().winId(), x=positions['x'], y=positions['y'], width=positions['w'],
                            height=positions['h'])
    pix.save("screenshot.png")

    # OCR识别
    cardname = pytesseract.image_to_string(ImageOps.invert(Image.open('screenshot.png').convert('L')), lang='eng',
                                           config='--psm 7')[:-1].replace('"', '""')

    # 连接数据库
    con = sqlite3.connect('name_id.db')
    data_base_eng = con.cursor()
    con1 = sqlite3.connect('ygocore.cdb')
    data_base_ch = con1.cursor()

    cardname_buffer = ''
    cardname_buffer_status = False

    if len(cardname) > 1:  # 查找英文数据库中对应的编号
        sql = 'SELECT id, name FROM data WHERE name = "{}"'.format(cardname)
        res = data_base_eng.execute(sql).fetchall()
        if len(res) != 1 and len(cardname) >= 10:
            sql = 'SELECT id, name FROM data WHERE name LIKE "{}%"'.format(cardname[:-1])
            res = data_base_eng.execute(sql).fetchall()

        if len(res) != 1 and len(cardname) >= 10:
            if cardname_buffer_status == True:
                cardname_overlap_status = True
                cardname_origin = cardname
                cardname = cardname[1:-1]
                for i in range(0, len(cardname_buffer) - 5):
                    cardname_overlap_status = True
                    j = 0
                    while i + j < len(cardname_buffer) and j < len(cardname):
                        if cardname_buffer[i + j] == cardname[j]:
                            j += 1
                        else:
                            cardname_overlap_status = False
                            break
                    if cardname_overlap_status == True and j < len(cardname):
                        cardname_buffer = cardname_buffer + cardname[j:]
                        break
                if cardname_overlap_status == True:
                    sql = 'SELECT id, name FROM data WHERE name LIKE "{}%"'.format(cardname_buffer)
                    res = cursor.execute(sql).fetchall()
                else:
                    cardname_buffer = cardname_origin[:-1]
                    cardname_buffer_status = True
            else:
                cardname_buffer = cardname[:-1]
                cardname_buffer_status = True

        if len(res) == 1:  # 中文数据库中查找
            cardname_buffer = ''
            cardname_buffer_status = False
            sql1 = 'SELECT name, desc FROM texts WHERE id = {} LIMIT 1'.format(res[0][0]) # 中文数据库中查找id对应的卡名
            res1 = data_base_ch.execute(sql1).fetchall()
            if len(res1) == 1:
                ans = ''
                print(res1)
                for i in res1[0]:
                    ans += i
                    ans += '\n'
                print(ans)
                ui.plainTextEdit.setPlainText(ans)
        else:
            ui.plainTextEdit.setPlainText('查询失败')


app = QApplication(sys.argv)
Mainwindow = QMainWindow()
ui = Ui_Dialog()
ui.setupUi(Mainwindow)
Mainwindow.show()
ui.pushButton_3.clicked.connect(getSettings)
ui.pushButton.clicked.connect(get_en)
ui.pushButton_2.clicked.connect(try_translate)
sys.exit(app.exec_())
